Angular Unit Testing

The unit test framework in Angular is called Jasmine. Jasmine is what creates the tests. These tests are then run in another framework called Karma.

When using Angular CLI, a unit test can be created by running

ng generate service testable

Generally the convention for unit test file names are

component.service.ts
component.service.spec.ts.

The test class requires the TestBed and TestableService services, which must be ES6 imported. Next we define the Jasmine functions that executes the test. These are Jasmine specific properties and must follow its syntax.

import { TestBed, inject } from '@angular/core/testing';
import { TestableService } from './testable.service';

describe('TestableService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [TestableService]
    });
  });

  it('should ...', inject([TestableService], (service: TestableService) => {
    expect(service).toBeTruthy();
  }));
});

The keywords to take note of (Jasmine functions) are “describe”, “beforeEach”, “it”, “expect”. After the test file is created, it can be called using Angular CLI.

ng test

The Karma test runner framework will run the tests.